//
//  XMChatImgSend.m
//  XMJJ_zmy
//
//  Created by 丁浩 on 2025/7/5.
//

#import "XMChatImgSend.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <Photos/Photos.h>
#import <PhotosUI/PhotosUI.h>
#import "UIImage+MultiFormat.h"

#define kTUIChatMediaSelectImageMax 9

@interface XMChatImgSend () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, PHPickerViewControllerDelegate>

@end

@implementation XMChatImgSend

static XMChatImgSend *chatImgSend;
static dispatch_once_t onceToken;
+ (instancetype)shareInstance {
    if (!chatImgSend) {
        dispatch_once(&onceToken, ^{
            chatImgSend = [[XMChatImgSend alloc] init];
        });
    }
    return chatImgSend;
}

- (void)_selectPhotoWithPresentVC:(XMBaseViewController *)presentVC {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (@available(iOS 14.0, *)) {
            PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
            configuration.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[ [PHPickerFilter imagesFilter]]];
            configuration.selectionLimit = kTUIChatMediaSelectImageMax;
            PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
            picker.delegate = self;
            picker.modalPresentationStyle = UIModalPresentationFullScreen;
            picker.view.backgroundColor = [UIColor whiteColor];
            [presentVC presentViewController:picker animated:YES completion:nil];
        }
        else {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
                picker.mediaTypes = @[@"public.image"];
                picker.delegate = self;
                [presentVC presentViewController:picker animated:YES completion:nil];
            }
        }
    });
}

- (void)cameraPhotoWithPresentVC:(XMBaseViewController *)presentVC {
    dispatch_async(dispatch_get_main_queue(), ^{
//        if (@available(iOS 14.0, *)) {
//            PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
//            configuration.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[ [PHPickerFilter imagesFilter]]];
//            configuration.selectionLimit = kTUIChatMediaSelectImageMax;
//            PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
//            picker.delegate = self;
//            picker.modalPresentationStyle = UIModalPresentationFullScreen;
//            picker.view.backgroundColor = [UIColor whiteColor];
//            [presentVC presentViewController:picker animated:YES completion:nil];
//        }
//        else {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
                picker.mediaTypes = @[@"public.image"];
                picker.delegate = self;
                [presentVC presentViewController:picker animated:YES completion:nil];
            }
//        }
    });
}

#pragma mark - PHPickerViewControllerDelegate
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results API_AVAILABLE(ios(14)) {
    dispatch_async(dispatch_get_main_queue(), ^{
      [picker dismissViewControllerAnimated:YES completion:nil];
      [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    });

    if (!results || results.count == 0) {
        return;
    }

//    PHPickerResult *result = [results firstObject];
    for (PHPickerResult *result in results) {
        [self _dealPHPickerResultFinishPicking:result];
    }
}

- (void)_dealPHPickerResultFinishPicking:(PHPickerResult *)result API_AVAILABLE(ios(14)) {
    NSItemProvider *itemProvoider = result.itemProvider;
    __weak typeof(self) weakSelf = self;
    if ([itemProvoider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeImage]) {
        [itemProvoider loadDataRepresentationForTypeIdentifier:(NSString *)kUTTypeImage
                                             completionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                 BOOL succ = YES;
                                                 NSString *message = nil;
                                                 if (error) {
                                                     succ = NO;
                                                     message = error.localizedDescription;
                                                 }
                                                 [weakSelf handleImagePick:succ message:message imageData:data];
                                               });
                                             }];
    }
    else if ([itemProvoider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeMPEG4]) {
//        [itemProvoider loadDataRepresentationForTypeIdentifier:(NSString *)kUTTypeMovie
//                                             completionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
//                                               dispatch_async(dispatch_get_main_queue(), ^{
//                                                 NSString *fileName = @"temp.mp4";
//                                                 NSString *tempPath = NSTemporaryDirectory();
//                                                 NSString *filePath = [tempPath stringByAppendingPathComponent:fileName];
//                                                 if ([NSFileManager.defaultManager isDeletableFileAtPath:filePath]) {
//                                                     [NSFileManager.defaultManager removeItemAtPath:filePath error:nil];
//                                                 }
//                                                 NSURL *newUrl = [NSURL fileURLWithPath:filePath];
//                                                 BOOL flag = [NSFileManager.defaultManager createFileAtPath:filePath contents:data attributes:nil];
//                                                 [weakSelf transcodeIfNeed:flag message:flag ? nil : @"video not found" videoUrl:newUrl];
//                                               });
//                                             }];
    }
    else if ([itemProvoider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeMovie]) {
        // Mov type: screen first
//        if ([self.listener respondsToSelector:@selector(onProvidePlaceholderVideoSnapshot:SnapImage:Completion:)]) {
//            [self.listener onProvidePlaceholderVideoSnapshot:@"" SnapImage:nil Completion:^(BOOL finished, TUIMessageCellData * _Nonnull placeHolderCellData) {
//                [itemProvoider loadDataRepresentationForTypeIdentifier:(NSString *)kUTTypeMovie
//                                                     completionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
//                                                       dispatch_async(dispatch_get_main_queue(), ^{
//                                                         // Non-mp4 format video, temporarily use mov suffix, will be converted to mp4 format later
//                                                         NSDate *datenow = [NSDate date];
//                                                         NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
//                                                         NSString *fileName = [NSString stringWithFormat:@"%@_temp.mov",timeSp];
//                                                         NSString *tempPath = NSTemporaryDirectory();
//                                                         NSString *filePath = [tempPath stringByAppendingPathComponent:fileName];
//                                                         if ([NSFileManager.defaultManager isDeletableFileAtPath:filePath]) {
//                                                             [NSFileManager.defaultManager removeItemAtPath:filePath error:nil];
//                                                         }
//                                                         NSURL *newUrl = [NSURL fileURLWithPath:filePath];
//                                                         BOOL flag = [NSFileManager.defaultManager createFileAtPath:filePath contents:data attributes:nil];
//                                                         [weakSelf transcodeIfNeed:flag message:flag ? nil : @"movie not found" videoUrl:newUrl placeHolderCellData:placeHolderCellData];
//                                                       });
//                                                     }];
//            }];
//        }
    } else {
        NSString *typeIdentifier = result.itemProvider.registeredTypeIdentifiers.firstObject;
        [itemProvoider loadFileRepresentationForTypeIdentifier:typeIdentifier
                                             completionHandler:^(NSURL *_Nullable url, NSError *_Nullable error) {
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                 UIImage *result;
                                                 NSData *data = [NSData dataWithContentsOfURL:url];
                                                 result = [UIImage imageWithData:data];

                                                 /**
                                                  * Can't get url when typeIdentifier is public.jepg on emulator:
                                                  * There is a separate JEPG transcoding issue that only affects the simulator (63426347), please refer to
                                                  * https://developer.apple.com/forums/thread/658135 for more information.
                                                  */
                                               });
                                             }];
    }
}

#pragma mark - UIImagePickerController
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info {
    __weak typeof(self) weakSelf = self;
    picker.delegate = nil;
    [picker dismissViewControllerAnimated:YES
                               completion:^{
                                 NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
                                 if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
                                     NSURL *url = nil;
                                     if (@available(iOS 11.0, *)) {
                                         url = [info objectForKey:UIImagePickerControllerImageURL];
                                     }
                                     else {
                                         url = [info objectForKey:UIImagePickerControllerReferenceURL];
                                     }

                                     BOOL succ = YES;
                                     NSData *imageData = nil;
                                     NSString *errorMessage = nil;
                                     if (url) {
                                         succ = YES;
                                         imageData = [NSData dataWithContentsOfURL:url];
                                     } else {
                                         succ = NO;
                                         errorMessage = @"image not found";
                                     }
                                     [weakSelf handleImagePick:succ message:errorMessage imageData:imageData];
                                 } else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
                                     NSURL *url = [info objectForKey:UIImagePickerControllerMediaURL];
                                     if (url) {
                                         [weakSelf transcodeIfNeed:YES message:nil videoUrl:url];
                                         return;
                                     }

//                                     /**
//                                      * In some cases UIImagePickerControllerMediaURL may be empty, use UIImagePickerControllerPHAsset
//                                      */
//                                     PHAsset *asset = nil;
//                                     if (@available(iOS 11.0, *)) {
//                                         asset = [info objectForKey:UIImagePickerControllerPHAsset];
//                                     }
//                                     if (asset) {
//                                         [self originURLWithAsset:asset
//                                                       completion:^(BOOL success, NSURL *URL) {
//                                                         [weakSelf transcodeIfNeed:success
//                                                                           message:success ? nil : @"origin url with asset not found"
//                                                                          videoUrl:URL];
//                                                       }];
//                                         return;
//                                     }

                                     /**
                                      * UIImagePickerControllerPHAsset may be empty, and other methods need to be used to obtain the original path of the video
                                      * file
                                      */
//                                     url = [info objectForKey:UIImagePickerControllerReferenceURL];
//                                     if (url) {
//                                         [weakSelf originURLWithRefrenceURL:url
//                                                                 completion:^(BOOL success, NSURL *URL) {
//                                                                   [weakSelf transcodeIfNeed:success
//                                                                                     message:success ? nil : @"origin url with asset not found"
//                                                                                    videoUrl:URL];
//                                                                 }];
//                                         return;
//                                     }

                                     // not support the video
//                                     [weakSelf transcodeIfNeed:NO message:@"not support the video" videoUrl:nil];
                                 }
                               }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Private Do task
- (void)handleImagePick:(BOOL)succ message:(NSString *)message imageData:(NSData *)imageData {
    static NSDictionary *imageFormatExtensionMap = nil;
    if (imageFormatExtensionMap == nil) {
        imageFormatExtensionMap = @{
            @(SDImageFormatUndefined) : @"",
            @(SDImageFormatJPEG) : @"jpeg",
            @(SDImageFormatPNG) : @"png",
            @(SDImageFormatGIF) : @"gif",
            @(SDImageFormatTIFF) : @"tiff",
            @(SDImageFormatWebP) : @"webp",
            @(SDImageFormatHEIC) : @"heic",
            @(SDImageFormatHEIF) : @"heif",
//            @(SDImageFormatPDF) : @"pdf",
//            @(SDImageFormatSVG) : @"svg",
//            @(SDImageFormatBMP) : @"bmp",
//            @(SDImageFormatRAW) : @"raw"
        };
    }

    dispatch_async(dispatch_get_main_queue(), ^{
      if (succ == NO || imageData == nil) {
//          if ([self.listener respondsToSelector:@selector(onProvideImageError:)]) {
//              [self.listener onProvideImageError:message];
//          }
          return;
      }

      UIImage *image = [UIImage imageWithData:imageData];
      NSData *data = UIImageJPEGRepresentation(image, 1);
//      NSString *path = [TUIKit_Image_Path stringByAppendingString:[self genImageName:nil]];
//      NSString *extenionName = [imageFormatExtensionMap objectForKey:@(image.sd_imageFormat)];
//      if (extenionName.length > 0) {
//          path = [path stringByAppendingPathExtension:extenionName];
//      }

        
      int32_t imageFormatSizeMax = 28 * 1024 * 1024;

      if (image.sd_imageFormat == SDImageFormatGIF) {
          imageFormatSizeMax = 10 * 1024 * 1024;
      }
     
      if (imageData.length > imageFormatSizeMax) {
          [MBProgressHUD showError:@"图片过大"];
//         if ([self.listener respondsToSelector:@selector(onProvideFileError:)]) {
//             [self.listener onProvideFileError:TIMCommonLocalizableString(TUIKitImageSizeCheckLimited)];
//         }
         return;
      }
    
      if (image.sd_imageFormat != SDImageFormatGIF) {
          UIImage *newImage = image;
          UIImageOrientation imageOrientation = image.imageOrientation;
          CGFloat aspectRatio = MIN(1920 / image.size.width, 1920 / image.size.height);
          CGFloat aspectWidth = image.size.width * aspectRatio;
          CGFloat aspectHeight = image.size.height * aspectRatio;
          UIGraphicsBeginImageContext(CGSizeMake(aspectWidth, aspectHeight));
          [image drawInRect:CGRectMake(0, 0, aspectWidth, aspectHeight)];
          newImage = UIGraphicsGetImageFromCurrentImageContext();
          UIGraphicsEndImageContext();
          data = UIImageJPEGRepresentation(newImage, 0.75);
      }
        
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Cache/ImgData"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = false;
        BOOL isDreExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
        if (!(isDir && isDreExist)) {
            NSError *error = nil;
            BOOL bCreaterDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
            if (!bCreaterDir) {
                NSLog(@"创建失败");
            }
        }
        NSString *dateStr = [[NSDate date] dateStringWithFormat:@"yyyy_MM_dd_HH_mm_ss"];
        path = [path stringByAppendingFormat:@"/%@.%@", dateStr, [imageFormatExtensionMap objectForKey:@(image.sd_imageFormat)]];

        XMWeakSelf;
        [[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
        weakSelf.imgSelectBlock ? weakSelf.imgSelectBlock(path) : nil;
//      if ([self.listener respondsToSelector:@selector(onProvideImage:)]) {
//          [self.listener onProvideImage:path];
//      }
    });
}

- (void)transcodeIfNeed:(BOOL)succ message:(NSString *)message videoUrl:(NSURL *)url {
    if (succ == NO || url == nil) {
//        [self handleVideoPick:NO message:message videoUrl:nil];
        return;
    }
//
    if ([url.pathExtension.lowercaseString isEqualToString:@"mp4"]) {
        [self handleVideoPick:succ message:message videoUrl:url];
        return;
    }
//
//    NSString *tempPath = NSTemporaryDirectory();
//    NSURL *urlName = [url URLByDeletingPathExtension];
//    NSURL *newUrl = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@%@.mp4", tempPath, [urlName.lastPathComponent stringByRemovingPercentEncoding]]];
//
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:newUrl.path]) {
//        NSError *error;
//        BOOL success = [fileManager removeItemAtPath:newUrl.path error:&error];
//        if (!success || error) {
//            NSAssert1(NO, @"removeItemFail: %@", error.localizedDescription);
//            return;
//        }
//    }
//
//    // mov to mp4
//    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
//    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
//    exportSession.outputURL = newUrl;
//    exportSession.outputFileType = AVFileTypeMPEG4;
//    exportSession.shouldOptimizeForNetworkUse = YES;
//
//    // intercept FirstTime VideoPicture
//    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
//    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
//    NSInteger duration = (NSInteger)urlAsset.duration.value / urlAsset.duration.timescale;
//    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
//    gen.appliesPreferredTrackTransform = YES;
//    gen.maximumSize = CGSizeMake(192, 192);
//    NSError *error = nil;
//    CMTime actualTime;
//    CMTime time = CMTimeMakeWithSeconds(0.5, 30);
//    CGImageRef imageRef = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
//    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
//    CGImageRelease(imageRef);
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if ([self.listener respondsToSelector:@selector(onProvidePlaceholderVideoSnapshot:SnapImage:Completion:)]) {
//            [self.listener onProvidePlaceholderVideoSnapshot:@"" SnapImage:image Completion:^(BOOL finished, TUIMessageCellData * _Nonnull placeHolderCellData) {
//                [exportSession exportAsynchronouslyWithCompletionHandler:^{
//                  switch ([exportSession status]) {
//                      case AVAssetExportSessionStatusFailed:
//                          NSLog(@"Export session failed");
//                          break;
//                      case AVAssetExportSessionStatusCancelled:
//                          NSLog(@"Export canceled");
//                          break;
//                      case AVAssetExportSessionStatusCompleted: {
//                          // Video conversion finished
//                          NSLog(@"Successful!");
//                          [self handleVideoPick:succ message:message videoUrl:newUrl placeHolderCellData:placeHolderCellData];
//                      }
//                          break;
//                      default:
//                          break;
//                  }
//                }];
//
//                [NSTimer tui_scheduledTimerWithTimeInterval:.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//                    if (exportSession.status == AVAssetExportSessionStatusExporting) {
//                        NSLog(@"exportSession.progress:%f",exportSession.progress);
//                        placeHolderCellData.videoTranscodingProgress = exportSession.progress;
//                    }
//                }];
//
//            }];
//        }
//        else {
//            [exportSession exportAsynchronouslyWithCompletionHandler:^{
//              switch ([exportSession status]) {
//                  case AVAssetExportSessionStatusCompleted: {
//                      // Video conversion finished
//                      NSLog(@"Successful!");
//                      [self handleVideoPick:succ message:message videoUrl:newUrl];
//                  } break;
//                  default:
//                      break;
//              }
//            }];
//        }
//    });
//
}

//- (void)transcodeIfNeed:(BOOL)succ message:(NSString *)message videoUrl:(NSURL *)url {//placeHolderCellData:(TUIMessageCellData*)placeHolderCellData {
//    if (succ == NO || url == nil) {
//        [self handleVideoPick:NO message:message videoUrl:nil];
//        return;
//    }
//
//    if ([url.pathExtension.lowercaseString isEqualToString:@"mp4"]) {
//        [self handleVideoPick:succ message:message videoUrl:url];
//        return;
//    }
//
//    NSString *tempPath = NSTemporaryDirectory();
//    NSURL *urlName = [url URLByDeletingPathExtension];
//    NSURL *newUrl = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@%@.mp4", tempPath, [urlName.lastPathComponent stringByRemovingPercentEncoding]]];
//
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    if ([fileManager fileExistsAtPath:newUrl.path]) {
//        NSError *error;
//        BOOL success = [fileManager removeItemAtPath:newUrl.path error:&error];
//        if (!success || error) {
//            NSAssert1(NO, @"removeItemFail: %@", error.localizedDescription);
//            return;
//        }
//    }
//
//    // mov to mp4
//    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
//    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetHighestQuality];
//    exportSession.outputURL = newUrl;
//    exportSession.outputFileType = AVFileTypeMPEG4;
//    exportSession.shouldOptimizeForNetworkUse = YES;
//
//    // intercept FirstTime VideoPicture
//    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
//    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
//    NSInteger duration = (NSInteger)urlAsset.duration.value / urlAsset.duration.timescale;
//    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
//    gen.appliesPreferredTrackTransform = YES;
//    gen.maximumSize = CGSizeMake(192, 192);
//    NSError *error = nil;
//    CMTime actualTime;
//    CMTime time = CMTimeMakeWithSeconds(0.5, 30);
//    CGImageRef imageRef = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
//    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
//    CGImageRelease(imageRef);
//
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if ([self.listener respondsToSelector:@selector(onProvidePlaceholderVideoSnapshot:SnapImage:Completion:)]) {
//            [exportSession exportAsynchronouslyWithCompletionHandler:^{
//              switch ([exportSession status]) {
//                  case AVAssetExportSessionStatusFailed:
//                      NSLog(@"Export session failed");
//                      break;
//                  case AVAssetExportSessionStatusCancelled:
//                      NSLog(@"Export canceled");
//                      break;
//                  case AVAssetExportSessionStatusCompleted: {
//                      // Video conversion finished
//                      NSLog(@"Successful!");
//                      [self handleVideoPick:succ message:message videoUrl:newUrl placeHolderCellData:placeHolderCellData];
//                  }
//                      break;
//                  default:
//                      break;
//              }
//            }];
//
//            [NSTimer tui_scheduledTimerWithTimeInterval:.1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//                if (exportSession.status == AVAssetExportSessionStatusExporting) {
//                    NSLog(@"exportSession.progress:%f",exportSession.progress);
//                    placeHolderCellData.videoTranscodingProgress = exportSession.progress;
//                }
//            }];
//        }
//        else {
//            [exportSession exportAsynchronouslyWithCompletionHandler:^{
//              switch ([exportSession status]) {
//                  case AVAssetExportSessionStatusCompleted: {
//                      // Video conversion finished
//                      NSLog(@"Successful!");
//                      [self handleVideoPick:succ message:message videoUrl:newUrl];
//                  } break;
//                  default:
//                      break;
//              }
//            }];
//        }
//    });
//
//}

- (NSString *)genImageName:(NSString *)uuid {
    NSString *identifier = [[V2TIMManager sharedInstance] getLoginUser];
    if (uuid == nil) {
        int value = arc4random() % 1000;
        uuid = [NSString stringWithFormat:@"%ld_%d", (long)[[NSDate date] timeIntervalSince1970], value];
    }

    NSString *name = [NSString stringWithFormat:@"%d_%@_image_%@", ImSDKAppId, identifier, uuid];
    return name;
}

- (NSString *)genVideoName:(NSString *)uuid {
    NSString *identifier = [[V2TIMManager sharedInstance] getLoginUser];
    if (uuid == nil) {
        uuid = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    }
    NSString *name = [NSString stringWithFormat:@"%d_%@_video_%@", ImSDKAppId, identifier, uuid];
    return name;
}

- (NSString *)genSnapshotName:(NSString *)uuid {
    NSString *identifier = [[V2TIMManager sharedInstance] getLoginUser];
    if (uuid == nil) {
        int value = arc4random() % 1000;
        uuid = [NSString stringWithFormat:@"%ld_%d", (long)[[NSDate date] timeIntervalSince1970], value];
    }
    NSString *name = [NSString stringWithFormat:@"%d_%@_snapshot_%@", ImSDKAppId, identifier, uuid];
    return name;
}

- (void)handleVideoPick:(BOOL)succ message:(NSString *)message videoUrl:(NSURL *)videoUrl {//placeHolderCellData:(TUIMessageCellData*)placeHolderCellData{
    if (succ == NO || videoUrl == nil) {
        return;
    }

    NSData *videoData = [NSData dataWithContentsOfURL:videoUrl];
    NSString *videoPath = [NSString stringWithFormat:@"%@%@_%u.mp4", TUIKit_Video_Path, [self genVideoName:nil],arc4random()];
    [[NSFileManager defaultManager] createFileAtPath:videoPath contents:videoData attributes:nil];

    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:videoUrl options:opts];
    NSInteger duration = (NSInteger)urlAsset.duration.value / urlAsset.duration.timescale;
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
    gen.appliesPreferredTrackTransform = YES;
    gen.maximumSize = CGSizeMake(192, 192);
    NSError *error = nil;
    CMTime actualTime;
    CMTime time = CMTimeMakeWithSeconds(0.5, 30);
    CGImageRef imageRef = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *image = [[UIImage alloc] initWithCGImage:imageRef];
    CGImageRelease(imageRef);

    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *imagePath = [TUIKit_Video_Path stringByAppendingFormat:@"%@_%u",[self genSnapshotName:nil],arc4random()];
    [[NSFileManager defaultManager] createFileAtPath:imagePath contents:imageData attributes:nil];

//    if ([self.listener respondsToSelector:@selector(onProvideVideo:snapshot:duration:placeHolderCellData:)]) {
//        [self.listener onProvideVideo:videoPath snapshot:imagePath duration:duration placeHolderCellData:placeHolderCellData];
//    }
}

@end
